﻿using System.IO;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering;
using UnityEngine.UI;
using UnityEngine.Video;
using Yoozoo.Managers.ResourceManagerV2.Runtime;

namespace Yoozoo.Modules.UI
{
    public class MediaPlayer : MonoBehaviour
	{
        public VideoPlayer VideoPlayer;
        
        public string VideoName;

        public bool PlayOnEnable = true;

        public RawImage RawImage;

        public CanvasScaler.ScreenMatchMode ScreenMatchMode;

        public int VideoWidth;

        public int VideoHeight;

        private RenderTexture temporaryRenderTexture;

        private int width;

        private int height;

        public void Awake()
        {
            VideoPlayer = GetComponent<VideoPlayer>();
            if (VideoPlayer == null)
                return;

            RawImage = GetComponent<RawImage>();

            if (VideoPlayer.clip == null && string.IsNullOrEmpty(VideoName))
                return;

            if (!string.IsNullOrEmpty(VideoName))
                SetVideoPlayerUrl(VideoName);

            SetRenderTextureSize(VideoWidth, VideoHeight);
            SetScreenMatchMode(ScreenMatchMode);
        }
        
        public void OnEnable()
        {
            if (PlayOnEnable && VideoPlayer)
                VideoPlayer.Play();
        }

        public void SetVideoPlayerUrl(string videoName)
        {
            VideoName = videoName;
            if (VideoPlayer == null)
                return;
            
            VideoPlayer.source = VideoSource.Url;
            if (Application.isEditor)
            {
                var url = "file:///" + Path.Combine(Application.dataPath, "../Movie/" + VideoName);
                VideoPlayer.url = url.Replace("\\", "/");
            }
            else
            {
                string filePath = Path.Combine(UMTResource.Resource.ReadWritePath, "Movie", VideoName);
                if (File.Exists(filePath))
                {
                    VideoPlayer.url = "file:///" + filePath;
                }
                else
                {
                    if (Application.platform == RuntimePlatform.Android)
                        VideoPlayer.url = Path.Combine(Application.streamingAssetsPath, "Movie", VideoName);
                    else
                        VideoPlayer.url = "file:///" + Path.Combine(Application.streamingAssetsPath, "Movie", VideoName);
                }
            }
        }

        public void Play()
        {
            if (VideoPlayer)
                VideoPlayer.Play();
        }

        public void PlayUrl(string url)
        {
            if (VideoPlayer == null)
                return;
            
            VideoPlayer.source = VideoSource.Url;
            VideoPlayer.url = url;
            VideoPlayer.Play();
        }

        public void Stop()
        {
            if (VideoPlayer)
                VideoPlayer.Stop();
        }

        public void SetRenderTextureSize(int renderTextureWidth, int renderTextureHeight)
        {
            if(VideoPlayer == null)
                VideoPlayer = GetComponent<VideoPlayer>();

            if (VideoPlayer == null)
                return;

            if(RawImage == null)
                RawImage = GetComponent<RawImage>();
            
            if (VideoPlayer.targetTexture != null)
                return;

            width = renderTextureWidth;
            height = renderTextureHeight;

            temporaryRenderTexture = RenderTexture.GetTemporary(renderTextureWidth, renderTextureHeight);
            temporaryRenderTexture.dimension = TextureDimension.Tex2D;
            //temporaryRenderTexture.antiAliasing = 0;
            temporaryRenderTexture.depthStencilFormat = GraphicsFormat.None;
            temporaryRenderTexture.useMipMap = false;
            temporaryRenderTexture.useDynamicScale = false;
            temporaryRenderTexture.enableRandomWrite = false;
            temporaryRenderTexture.wrapMode = TextureWrapMode.Clamp;
            temporaryRenderTexture.filterMode = FilterMode.Bilinear;
            temporaryRenderTexture.anisoLevel = 0;

            VideoPlayer.targetTexture = temporaryRenderTexture;
            RawImage.texture = temporaryRenderTexture;
        }

        public void SetScreenMatchMode(CanvasScaler.ScreenMatchMode screenMatchMode)
        {
            if (width == 0 || height == 0)
                return;

            if (RawImage == null)
                RawImage = GetComponent<RawImage>();

            if (RawImage == null)
                return;

            if (screenMatchMode == CanvasScaler.ScreenMatchMode.Expand)
            {
                // 扩展，撑满全屏，但是视频只显示部分
                float aspectRatio = (float)height / width;
                var size = RawImage.rectTransform.rect.size;
                float uiAspectRatio = size.y / size.x;
                if (aspectRatio > uiAspectRatio)
                {
                    size.y = size.x * aspectRatio;
                }
                else
                {
                    size.x = size.y / aspectRatio;
                }

                RawImage.rectTransform.anchorMin = new Vector2(0.5f, 0.5f);
                RawImage.rectTransform.anchorMax = new Vector2(0.5f, 0.5f);
                RawImage.rectTransform.pivot = new Vector2(0.5f, 0.5f);
                RawImage.rectTransform.sizeDelta = size;
            }
            else if (screenMatchMode == CanvasScaler.ScreenMatchMode.Shrink)
            {
                // 缩小，会留黑边，但是视频完整显示
                float aspectRatio = (float)height / width;
                var size = RawImage.rectTransform.rect.size;
                float uiAspectRatio = size.y / size.x;
                if (aspectRatio > uiAspectRatio)
                {
                    size.x = size.y / aspectRatio;
                }
                else
                {
                    size.y = size.x * aspectRatio;
                }

                RawImage.rectTransform.anchorMin = new Vector2(0.5f, 0.5f);
                RawImage.rectTransform.anchorMax = new Vector2(0.5f, 0.5f);
                RawImage.rectTransform.pivot = new Vector2(0.5f, 0.5f);
                RawImage.rectTransform.sizeDelta = size;
            }
        }

        void OnDestroy()
        {
            if (temporaryRenderTexture)
            {
                RenderTexture.ReleaseTemporary(temporaryRenderTexture);
                temporaryRenderTexture = null;
            }
        }
    }
}
